package org.jeecg.chase.common.dataaccess.supper;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.JdbcUtils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author leikai
 * @version 1.0
 * @description: 数据库查询结果驼峰匹配
 * @date 2021/07/01/0001 17:07
 */
public class HumpColumnRowMapper implements RowMapper {
    /**
     * 驼峰key字符串容器
     */
    final StringBuilder camelKey = new StringBuilder();

    @Override
    public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
        Map<String, Object> camelKeyMap = new HashMap<String, Object>();
        int column = rs.getMetaData().getColumnCount();
        for (int i = 1; i <= column; i++) {
            camelKey.delete(0, camelKey.length());
            String columnLabel = rs.getMetaData().getColumnLabel(i).toLowerCase();
            if (!columnLabel.contains("_")) {
                camelKeyMap.put(columnLabel, JdbcUtils.getResultSetValue(rs, i));
                continue;
            }
            for (int j = 0, len = columnLabel.length(); j < len; j++) {
                char c = columnLabel.charAt(j);
                if (c != '_') {
                    camelKey.append(c);
                    continue;
                }
                if (++j < len) {
                    camelKey.append(Character.toUpperCase(columnLabel.charAt(j)));
                }
            }
            camelKeyMap.put(camelKey.toString(), JdbcUtils.getResultSetValue(rs, i));
        }
        return camelKeyMap;
    }
}
